package com.lsongh.springboot2.controller;

import com.lsongh.springboot2.entity.News;
import com.lsongh.springboot2.entity.Result;
import com.lsongh.springboot2.service.NewsService;
import com.lsongh.springboot2.service.UserService;
import com.lsongh.springboot2.utils.ResultUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController
public class NewsController {

    @Autowired
    NewsService newsService;

    @Autowired
    UserService userService;

    /**
     * 获取所有的新闻
     * @return
     */
    @GetMapping("news/findAll")
    public Result<News> findAll(@RequestParam("name") String name){
        if (name == ""){
            List<News> list = newsService.findAllNews(0);
            if (list.size()>0){
                for (News news:list) {
                    news.setNewsUserName(userService.findOne(news.getNewsUserId()).getName());
                }
            }
            return ResultUtil.success(list);
        }else {
            List<News> list = newsService.findAllNewsByName(0,name);
            if (list.size()>0){
                for (News news:list) {
                    news.setNewsUserName(userService.findOne(news.getNewsUserId()).getName());
                }
            }
            return ResultUtil.success(list);
        }

    }

    /**
     * 假删除一条新闻
     * @param id
     * @return
     */
    @DeleteMapping("news/delete/{id}")
    public Result<String> deleteNewById(@PathVariable("id") int id){
        newsService.deleteNewById(id);
        return ResultUtil.success("删除成功");
    }
    /**
     * 修改新闻
     */
    @PostMapping("news/update")
    public Result<String> updateNews(@RequestBody News news){
        newsService.save(news);
        return ResultUtil.success("修改成功");
    }

    /**
     * 添加新闻成功
     * @param news
     * @return
     */
    @PostMapping("news/add")
    public Result<String> addNews(@RequestBody News news){
        newsService.save(news);
        return ResultUtil.success("添加成功");
    }

    @PostMapping("news/likes/add/{id}")
    public Result<String>  addNewsLike(@PathVariable("id") int id){
        newsService.addNewLikesById(id);
        return ResultUtil.success("已收藏");
    }
}
